package com.lb.config;
import com.lb.annotation.MongoSwitch;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.text.MessageFormat;

/**
 * 功能描述: mongoDb数据源切换<br>
 * @Author: Edward
 * @Date: 2021/7/3 14:58
 */
@Component
@Aspect
@Order(value = -99)
@Slf4j
public class MongoDbSwitch {

  @Pointcut("@annotation(com.lb.annotation.MongoSwitch)")
  public void mongoSwitch() {}

  @Before("mongoSwitch()")
  public void before(JoinPoint point) {
    try {
      MethodSignature methodSignature = (MethodSignature) point.getSignature();
      Method method =
          point
              .getTarget()
              .getClass()
              .getMethod(methodSignature.getName(), methodSignature.getParameterTypes());
      MongoSwitch mongoSwitch = method.getAnnotation(MongoSwitch.class);
      log.info(MessageFormat.format("切换 {0}数据源", mongoSwitch.value()));
      MongoDbContext.setMongoDbFactory(mongoSwitch.value());
    } catch (Exception e) {
      log.error("==========>前置mongo数据源切换异常", e);
    }
  }

  @After("mongoSwitch()")
  public void after(JoinPoint point) {
    try {
      log.info("移除mongo数据源上下文");
      MongoDbContext.removeMongoDbFactory();
    } catch (Exception e) {
      log.error("==========>后置mongo数据源切换异常", e);
    }
  }
}